require('dotenv').config();
const { Web3 } = require('web3');
const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');

// 连接 Ganache 或 Hardhat 本地节点
const web3 = new Web3("http://127.0.0.1:7545");

// 读取 ABI 与合约地址
const artifactPath = path.resolve(__dirname, 'E:/Vue3/vite-project/artifacts/contracts/DonationPlatform.sol/DonationPlatform.json');
const artifact = JSON.parse(fs.readFileSync(artifactPath, 'utf8'));
const abi = artifact.abi;

// 合约部署地址
const contractAddress = '0x1f936366c9b21fC9343BC2DC710031aa01be072E';
const contract = new web3.eth.Contract(abi, contractAddress);

// 本地测试账户地址
const account = '0xe697615b4B70830d074585E097F5FA201e28c0A8';

function isValidAddress(addr) {
  return /^0x[a-fA-F0-9]{40}$/.test(addr);
}

// 主函数：从数据库读取数据并上链
async function uploadProjects() {
  const connection = await mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'donation_platform'
  });

  const [rows] = await connection.execute('SELECT * FROM hot_projects');

  for (const row of rows) {
    try {
      const walletAddressRaw = row.walletAddress || '';
      const walletAddress = walletAddressRaw.trim().toLowerCase();

      if (!isValidAddress(walletAddress)) {
        console.error(`❌ 无效地址，跳过项目: ${row.name} - ${walletAddressRaw}`);
        continue;
      }

      const goalWei = web3.utils.toWei((row.goal || 0).toString(), 'ether');
      const raisedWei = web3.utils.toWei((row.raised || 0).toString(), 'ether');

      const progress = parseInt(row.progress) || 0;
      const donors = parseInt(row.donors) || 0;
      const tag = parseInt(row.tag) || 0;
      const status = parseInt(row.status) || 0;

      const tx = await contract.methods.createProject(
        row.name,
        row.shortDescription || '',
        row.description || '',
        row.image || '',
        goalWei,
        raisedWei,
        progress,
        donors,
        tag,
        status,
        walletAddress
      ).send({ from: account, gas: 3000000 });

      console.log(`✅ 上传成功: ${row.name} - Tx: ${tx.transactionHash}`);

    } catch (err) {
      console.error(`❌ 上传失败: ${row.name} - 错误: ${err.message}`);
    }
  }

  await connection.end();
}

uploadProjects().catch(console.error);
